#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
根据图片路径清单文件，从storage目录复制图片到temp目录
"""

import os
import shutil
from pathlib import Path
import logging

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)


def copy_images_by_list(
    list_file_path: str = "temp/picknbuy2419941dd5b73c-fafe-49bb-ad.txt",
    source_base_path: str = "storage/vehicles",
    target_base_path: str = "temp/copied_images"
):
    """
    根据图片路径清单文件，从源目录复制图片到目标目录
    
    Args:
        list_file_path: 图片路径清单文件路径
        source_base_path: 源图片基础路径
        target_base_path: 目标复制路径
    """
    
    # 转换为绝对路径
    script_dir = Path(__file__).parent.parent  # chuhai_scraper根目录
    list_file = script_dir / list_file_path
    source_base = script_dir / source_base_path
    target_base = script_dir / target_base_path
    
    logger.info(f"开始处理图片清单文件: {list_file}")
    logger.info(f"源路径: {source_base}")
    logger.info(f"目标路径: {target_base}")
    
    # 检查清单文件是否存在
    if not list_file.exists():
        logger.error(f"清单文件不存在: {list_file}")
        return False
    
    # 检查源目录是否存在
    if not source_base.exists():
        logger.error(f"源目录不存在: {source_base}")
        return False
    
    # 创建目标目录
    target_base.mkdir(parents=True, exist_ok=True)
    
    # 统计信息
    total_files = 0
    copied_files = 0
    missing_files = 0
    failed_files = 0
    
    try:
        with open(list_file, 'r', encoding='utf-8') as f:
            for line_num, line in enumerate(f, 1):
                line = line.strip()
                if not line:
                    continue
                
                total_files += 1
                
                # 构建源文件路径
                source_file = source_base / line
                
                # 构建目标文件路径（保持相同的目录结构）
                target_file = target_base / line
                
                # 创建目标文件的父目录
                target_file.parent.mkdir(parents=True, exist_ok=True)
                
                try:
                    if source_file.exists():
                        # 复制文件
                        shutil.copy2(source_file, target_file)
                        copied_files += 1
                        if copied_files % 100 == 0:
                            logger.info(f"已复制 {copied_files} 个文件...")
                    else:
                        logger.warning(f"第{line_num}行: 源文件不存在 - {source_file}")
                        missing_files += 1
                        
                except Exception as e:
                    logger.error(f"第{line_num}行: 复制文件失败 - {line} -> {e}")
                    failed_files += 1
    
    except Exception as e:
        logger.error(f"读取清单文件失败: {e}")
        return False
    
    # 输出统计结果
    logger.info(f"处理完成!")
    logger.info(f"总文件数: {total_files}")
    logger.info(f"成功复制: {copied_files}")
    logger.info(f"文件缺失: {missing_files}")
    logger.info(f"复制失败: {failed_files}")
    
    return True


def main():
    """主函数"""
    copy_images_by_list()


if __name__ == "__main__":
    main()
